package adverts_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"github.com/gin-gonic/gin"
)

type AdvertRequest struct {
	Title  string `json:"title" binding:"required" msg:"请输入标题"`       // 标题
	Href   string `json:"href" binding:"required,url" msg:"链接地址非法"`   // 跳转链接
	Images string `json:"images" binding:"required,url" msg:"图片地址非法"` // 图片
	IsShow bool   `json:"is_show" binding:"required" msg:"请选择是否显示"`   // 是否展示
}

// AdvertsCreateView 广告添加
// @Tags 广告管理
// @Summary 广告添加
// @Description 广告添加
// @Param data body AdvertRequest true "表示多个参数"
// @Router /api/adverts [post]
// @Produce json
// @Success 200 {object} http.Response{}
func (AdvertsApi) AdvertsCreateView(c *gin.Context) {
	var cr AdvertRequest
	// 二选一
	//err := c.ShouldBindBodyWith(&cr, binding.JSON)
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		http.FailWithError(err, &cr, c)
		return
	}
	// 判断重复
	var adverts models.AdvertModel
	err = common.DB.Take(&adverts, "title = ?", cr.Title).Error
	if err == nil {
		http.FailWithMessage("广告名称重复", c)
		return
	}

	advertsData := &models.AdvertModel{
		Title:  cr.Title,
		Href:   cr.Href,
		Images: cr.Images,
		IsShow: cr.IsShow,
	}

	err = common.DB.Create(advertsData).Error
	if err != nil {
		common.Log.Error(err)
		http.FailWithMessage("添加失败", c)
		return
	}
	http.IsOkWithMessage("添加广告成功", c)
}
